/*
 * MediaChunkIndex.cpp
 *
 *  Created on: 2013-1-11
 *      Author: terry
 */

#include "stdafx.h"
#include "MediaChunkIndex.h"
#include <algorithm>
#include <functional>


MediaChunkIndexTable::MediaChunkIndexTable()
{

}

MediaChunkIndexTable::~MediaChunkIndexTable()
{

}

int64_t MediaChunkIndexTable::getDuration()
{
    if (size() < 3)
    {
        return 0;
    }

    iterator it = begin();
    it ++;

    const MediaChunkIndex& firstIndex = *it;
    const MediaChunkIndex& lastIndex = back();
    return lastIndex.header.timestamp - firstIndex.header.timestamp;
}


struct IndexPred : public std::binary_function< MediaChunkIndex, MediaChunkIndex, bool >
{
    bool operator () (const MediaChunkIndex& index, const MediaChunkIndex& second) const
    {
        return (index.offset < second.offset);
    }
};

bool MediaChunkIndexTable::find(int64_t offset, MediaChunkIndex& index)
{
    bool found = false;
    index.offset = offset;
    iterator it = std::lower_bound(begin(), end(), index, IndexPred());
    if (it != end())
    {
        index = *it;
        found = true;
    }
    return found;
}

bool MediaChunkIndexTable::parseFromFile(BYTE* buffer, int64_t length)
{
    clear();

    int64_t pos = sizeof(MediaFileHeader);
    while (pos <= (length - sizeof(MediaChunkHeader)))
    {
        MediaChunkHeader* pHeader = (MediaChunkHeader*)(buffer + pos);

        MediaChunkIndex index;
        index.offset = pos;
        index.header = *pHeader;

        push_back(index);

        pos += sizeof(MediaChunkHeader);
        pos += index.header.length;
    }
    return !empty();
}